//
//  WNMyVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/5.
//

import UIKit

class WNMyVC: WNBaseVC {
    
    lazy var userHeaderView: MeUserHeaderView = {
        return MeUserHeaderView(frame: CGRect(x: 0, y: 0, width: ScreenW, height: 201))
    }()
    
    lazy var myTabView: WNTableView = {
        let tab = WNTableView(frame: .zero, style: .grouped)
        tab.register(MeUserCell.self, forCellReuseIdentifier: MeUserCell.identifier)
        tab.delegate = self
        tab.dataSource = self
        tab.tableHeaderView = userHeaderView
        return tab
    }()
        
    var userModel: UserDetailModel? {
        didSet {
            userHeaderView.model = userModel
        }
    }
    
    var limitedArr = [RechargeDetailModel]()
    
    var limitedModel: RechargeDetailModel? {
        didSet {
            myTabView.reloadRows(at: [IndexPath.init(row: 1, section: 0)], with: .none)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        dataRequest()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        wn_hidNavView()
        view.addSubview(myTabView)
        myTabView.snp.makeConstraints { make in
            make.top.equalTo(StatusBarHeight)
            make.left.right.equalTo(0)
            make.bottom.equalTo(-TabBarTotalHeight)
        }
    }
    
    override func dataConfig() {
        pageName = "我的"
        userModel = getUser()
        getLimitedRequest()
    }
    
    override func handleNoti() {
        NotificationCenter.default.addObserver(forName: WNNotiName.loginNoti, object: nil, queue: nil) { [weak self] not in
            self?.getLimitedRequest()
        }
        NotificationCenter.default.addObserver(forName: WNNotiName.rechargeNoti, object: nil, queue: nil) { [weak self] not in
            self?.getLimitedRequest()
        }
    }
    
    func showHeader() {
        if let str = userModel?.avatar, !str.isEmpty {
            let photo = GKPhoto.init()
            photo.url = URL.init(string: str)!
            let browser = GKPhotoBrowser(photos: [photo], currentIndex: 0)
            browser.showStyle = .none
            browser.show(fromVC: self)
        }
    }
    
    func handleLimitedArr() {
        if limitedArr.count == 0 {
            limitedModel = nil
        }else {
            if limitedArr.count == 1 {
                limitedModel = limitedArr[0].expireTime == 0 ? nil : limitedArr[0]
            }else {
                let exArr = limitedArr.filter({$0.expireTime != 0})
                if exArr.count == 0 {
                    limitedModel = nil
                }else if exArr.count == 1 {
                    limitedModel = exArr.first
                }else {
                    limitedModel = exArr.sorted(by: {$0.gold > $1.gold}).first
                }
            }
        }
    }
}

extension WNMyVC: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int { 2 }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? 5 : 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MeUserCell.identifier, for: indexPath) as! MeUserCell
        cell.userType = indexPath.section*20+indexPath.item
        if indexPath.section == 0 && indexPath.item == 1 && limitedModel == nil {
            cell.topupTaskView.model = limitedModel
            cell.topupTaskView.topupClosure = { model in
                if let m = model {
                    WNBuriedManager.shared.logProductItem(m.productId ?? "", m.productName ?? "", m.price)
                    WNLimitedPayManager.shared.creatLimitedRechargeOrder(m.productId ?? "", m.productName ?? "", m.productIds ?? "", m.price)
                }
            }
            cell.topupTaskView.expireClosure = { [weak self] in
                self?.getLimitedRequest()
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = section == 1 ? .white : .init(named: "white_F7F7F7")
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0:
            switch indexPath.item {
            case 0:
                return 0
            case 1:
                return limitedModel == nil ? 0 : (scaleWidth(ScreenW-40)*0.29)+12
            default: return 60
            }
//        case 1:
//            return (scaleWidth(ScreenW)*0.38)
        default:
            return 60
        }
    }
}

extension WNMyVC {
    
    func dataRequest() {
        let group = DispatchGroup()
        group.enter()
        provider_user.rx.request(.checkTicket)
            .asObservable().mapModel(BaseModel<[TicketModel]>.self)
            .subscribe(onNext: { (model) in
                guard model.code == 0 else { return group.leave() }
                saveHasCheck(true)
                if let arr = model.data, arr.filter({$0.status == 2}).count > 0 {
                    saveHasCheck(false)
                }
                group.leave()
            }, onError: { (error) in
                group.leave()
            }).disposed(by: rx.disposeBag)
        group.enter()
        provider_login.rx.request(.checkUser)
            .asObservable().mapModel(BaseModel<UserDetailModel>.self)
            .subscribe(onNext: { (model) in
                guard model.code == 0 else { return group.leave() }
                if let data = model.data {
                    saveUser(user: data)
                    setKeyUserId(data.userId ?? "")
                    WNSingleData.shared.userGold = data.gold
                }
                group.leave()
            }, onError: { (error) in
                group.leave()
            }).disposed(by: rx.disposeBag)
        group.notify(queue: DispatchQueue.main) { [weak self] in
            self?.userModel = getUser()
            self?.userHeaderView.goldView.setTopType(1, WNSingleData.shared.userGold)
            self?.myTabView.reloadRows(at: [IndexPath.init(item: 2, section: 0)], with: .none)
        }
    }

    func getLimitedRequest() {
        getUserGold { [weak self] gold in
            self?.userHeaderView.goldView.setTopType(1, WNSingleData.shared.userGold)
        }
        provider_setting.rx.request(.rechargeLimited)
            .asObservable().mapModel(BaseModel<[RechargeDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                self?.limitedArr.removeAll()
                if let arr = model.data {
                    self?.limitedArr = arr
                    self?.handleLimitedArr()
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("檢查網路連線")
            }).disposed(by: rx.disposeBag)
    }
}
